const { sqlite3 } = require('../../mysql')

// 提交订单数据
const submitOrder = async (ctx) => {
  console.log('接收订单')
  console.log(ctx.request.body)
  user_id = ctx.request.body.openId
  orderNum = ctx.request.body.orderNum
  sel_cate = ctx.request.body.sel_cate
  sel_detail = ctx.request.body.sel_detail
  orderStatus = ctx.request.body.orderStatus
  sel_time = ctx.request.body.sel_time
  create_time = ctx.request.body.create_time
  modify_time = ''

  const data = await sqlite3('order').where({
    orderNum,
  }).insert({
    user_id,
    orderNum,
    sel_cate,
    sel_detail,
    sel_time,
    orderStatus,
    create_time,
    modify_time
  })
  if (data) {
    ctx.body = {
      // category: category,
      result: true,
    }
  } else {
    ctx.body = {
      // category: category,
      result: false,
    }
  }
}


// 获取订单数据
const getOrder = async (ctx) => {
  console.log('获取订单')
  console.log(ctx.query.openId)
  const user_id = ctx.query.openId
  const data = await sqlite3('order').where({
    user_id,
    // orderStatus: !0
  }).orderBy('id', 'desc').select()
  console.log(data)
  if (data) {
    ctx.body = {
      orderlist: data,
      result: true,
    }
  } else {
    ctx.body = {
      result: false,
    }
  }
}


// 取消订单数据
const delOrder = async (ctx) => {
  console.log('取消订单')
  // console.log(ctx.request.body)
  const id = ctx.request.body.orderId
  const user_id = ctx.request.body.openId
  console.log(id, user_id);
  const data = await sqlite3('order').where({
    id,
    user_id
  }).update({
    orderStatus: 0
  })
  if (data) {
    ctx.body = {
      result: true,
    }
  } else {
    ctx.body = {
      result: false,
    }
  }
}


// 管理平台获取订单数据
const getOrderList = async (ctx) => {
  let formData = ctx.query
  let offset = (formData.page - 1) * formData.limit
  let keyword = formData.query
  let limitdata = {}
  let data = {}
  if (keyword) {
    // console.log('query:', keyword)
    limitdata = await sqlite3('order').select()
    data = await sqlite3('order').where('id', 'LIKE', '%' + keyword + '%')
      .orderBy('id', 'desc').select().limit(formData.limit).offset(offset)
  } else {
    limitdata = await sqlite3('order').select()
    data = await sqlite3('order').orderBy('id', 'desc')
      .select().limit(formData.limit).offset(offset)
  }
  if (data) {
    ctx.body = {
      code: 200,
      item: data,
      total: limitdata.length
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

// 管理平台更新订单数据
const orderUpdate = async (ctx) => {
  console.log('ctx:', ctx.request.body)
  let formData = ctx.request.body
  const data = await sqlite3('order')
    .where('id', formData.id)
    .update(formData)
  // console.log(data)
  if (data) {
    ctx.body = {
      code: 200,
      data: "success"
    }
  } else {
    ctx.body = {
      code: false
    }
  }
}

module.exports = { submitOrder, getOrder, delOrder, getOrderList, orderUpdate }
